package com.liy.teaching.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liy.teaching.entity.ProductEntity;
import com.liy.teaching.mapper.ProductMapper;
import com.liy.teaching.service.ProductService;
import com.liy.teaching.util.JSONUtil;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * 商品服务
 **/
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductEntity> implements ProductService {

    //前缀
    private static final String KEY_PREFIX = "product:";

    //  格式化一下
    private static String buildKey(String id) {
        return KEY_PREFIX + id;  // product:商品ID
    }

    @Resource(name = "redisTemplate")
    private ValueOperations<Serializable, String> redisOperations;


    /**
     * 重载 getById(id)  做第一点增强
     */
    @Override
    public ProductEntity getById(Serializable id) {

        String redisKey = buildKey(String.valueOf(id));  // 根据ID 构建rediskey

        String redisValue = redisOperations.get(redisKey);  // 2.根据redisKey从缓存中获取对象

        if (redisValue != null) {  // 3.如果缓存对象不为空，直接返回

            return JSONUtil.parseObject(redisValue, ProductEntity.class); //直接返回;

        } else {  // 4.如果缓存对象为空，进行数据库查询

            ProductEntity product = getBaseMapper().selectById(id); // 从数据库中查

//            if(product !=null){  // 5.如果从数据库查询出的对象不为空，则放入缓存
//                String jsonString = JSONUtil.toJSONString(product);
//                redisOperations.set(redisKey, jsonString);
//                return product;
//            }
//            return null;

            String jsonString = JSONUtil.toJSONString(product);
            redisOperations.set(redisKey, jsonString);
            return product;

        }


    }


}
